package com.edu.thread.sync;

public class PrintAB_01 {

    public static void main(String[] args) {
        ShareData1 shareData1 = new ShareData1();

        new Thread(new Runnable() {
            @Override
            public void run() {
                shareData1.printA();
            }
        }).start();

        new Thread(new Runnable() {
            @Override
            public void run() {
                shareData1.printB();
            }
        }).start();


    }
}

class ShareData1{
    private boolean flag = true;

    Object lock = new Object();

    public void printA(){
        while (true){
            synchronized (lock){
                while (!flag){
                    try {
                        lock.wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                System.out.println("A");
                flag = false;
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                lock.notifyAll();
            }
        }

    }

    public void printB(){
        while (true){
            synchronized (lock){
                while (flag){
                    try {
                        lock.wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                System.out.println("B");
                flag = true;
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                lock.notifyAll();
            }
        }
    }

}
